const state = {
  openTabs: [
    {
      id: 'dashboard',
      title: '仪表盘',
      route: '/dashboard',
      closable: false
    }
  ],
  activeTab: 'dashboard',
  cachedViews: ['Dashboard'],
  loading: false,
  loadingText: '',
  sidebarCollapsed: false
}

const mutations = {
  ADD_TAB(state, tab) {
    const exists = state.openTabs.find(t => t.id === tab.id)
    if (!exists) {
      state.openTabs.push({
        ...tab,
        closable: tab.id !== 'dashboard' // 仪表盘不可关闭
      })
    }
    state.activeTab = tab.id
  },
  
  REMOVE_TAB(state, tabId) {
    const index = state.openTabs.findIndex(t => t.id === tabId)
    if (index > -1 && state.openTabs[index].closable) {
      // 如果只剩一个标签
      if (state.openTabs.length === 1) {
        // 重置为仪表盘
        state.openTabs = [
          {
            id: 'dashboard',
            title: '仪表盘',
            route: '/dashboard',
            closable: false
          }
        ]
        state.activeTab = 'dashboard'
      } else {
        // 删除标签
        const wasActive = state.activeTab === tabId
        state.openTabs.splice(index, 1)
        
        // 如果删除的是当前激活的标签，切换到相邻的标签
        if (wasActive) {
          // 优先选择后一个标签，如果没有则选择前一个
          const newIndex = index < state.openTabs.length ? index : index - 1
          state.activeTab = state.openTabs[Math.max(0, newIndex)].id
        }
      }
    }
  },
  
  SET_ACTIVE_TAB(state, tabId) {
    state.activeTab = tabId
  },
  
  ADD_CACHED_VIEW(state, viewName) {
    if (!state.cachedViews.includes(viewName)) {
      state.cachedViews.push(viewName)
    }
  },
  
  REMOVE_CACHED_VIEW(state, viewName) {
    const index = state.cachedViews.indexOf(viewName)
    if (index > -1) {
      state.cachedViews.splice(index, 1)
    }
  },
  
  SET_LOADING(state, { loading, text = '' }) {
    state.loading = loading
    state.loadingText = text
  },
  
  TOGGLE_SIDEBAR(state) {
    state.sidebarCollapsed = !state.sidebarCollapsed
  }
}

const actions = {
  addTab({ commit }, tab) {
    commit('ADD_TAB', tab)
    if (tab.componentName) {
      commit('ADD_CACHED_VIEW', tab.componentName)
    }
  },
  
  removeTabAction({ commit }, tabId) {
    commit('REMOVE_TAB', tabId)
  },
  
  setActiveTab({ commit }, tabId) {
    commit('SET_ACTIVE_TAB', tabId)
  },
  
  showLoading({ commit }, text) {
    commit('SET_LOADING', { loading: true, text })
  },
  
  hideLoading({ commit }) {
    commit('SET_LOADING', { loading: false })
  },
  
  toggleSidebar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  
  showNewConnectionDialog({ dispatch }) {
    dispatch('addTab', {
      id: `connection_${Date.now()}`,
      title: '新建连接',
      route: '/new-connection'
    })
  },
  
  openSettings({ dispatch }, section) {
    dispatch('addTab', {
      id: 'settings',
      title: '设置',
      route: `/settings?section=${section}`
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}